<template>
  <el-card>
     <!-- 面包屑导航 -->
    <el-breadcrumb  separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>基本资料</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 表单 -->
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="80px" style="width: 500px;margin-top: 30px">
      <el-form-item label="登录名称">
        <el-input disabled></el-input>
      </el-form-item>
       <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="form.nickname"></el-input>
      </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateInfo">提交修改</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { reqUpdateUserInfo } from '@/api/user'
import { mapState, mapActions } from 'vuex'
export default {
  name: 'UserInfo',
  computed: {
    ...mapState('user', ['userInfo'])
  },
  async created () {
    //  执行获取个人资料的action, 获取完毕后再赋值
    // 此处的await指向阻塞后续的赋值的代码
    await this.getUserInfo()
    // console.log('再赋值')
    this.form = { ...this.userInfo }
    console.log('获取资料完成')
  },
  data () {
    return {
      // 表单关联的数据
      form: {
        nickname: '',
        email: ''
      },
      // 校验规则
      formRules: {
        nickname: [
          { required: true, message: '昵称不能为空', trigger: ['blur', 'change'] },
          { pattern: /^\S{1,10}$/, message: '昵称是1-10个非空字符', trigger: ['blur', 'change'] }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: ['blur', 'change'] },
          { pattern: /^([a-z0-9_.-]+)@([\da-z.-]+)\.([a-z.]{2,6})$/, message: '邮箱格式不正确', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    ...mapActions('user', ['getUserInfo']),
    // 重置
    reset () {
      // 将vuex中的数据重新赋值一次给 form
      this.form = { ...this.userInfo }
    },
    // 更新资料
    updateInfo () {
      // 1. 预校验
      this.$refs.formRef.validate(async boo => {
        if (!boo) return ''
        // 2. 发送请求
        const { data } = await reqUpdateUserInfo(this.form)
        // 3. 提示
        if (data.code !== 0) return this.$message.error(data.message)
        this.$message.success(data.message)
        // 4. 重新渲染 将vuex中的数据重新获取 调用getUserInfo
        this.getUserInfo()
      })
    }
  }
}
</script>

<style>

</style>
